#!/bin/bash
set -xeuo pipefail
set -o errexit

:<<EOF
https://blog.csdn.net/ale2012/article/details/82702128
https://www.cnblogs.com/personsiglewine/p/12510845.html
EOF

# 注册备份还原仓库
curl -XPUT http://localhost:9200/_snapshot/backup?pretty -H 'Content-Type: application/json' -d'
{
    "type": "fs",
    "settings": {
        "location": "/opt/backup",
        "max_snapshot_bytes_per_sec" : "50mb",
        "max_restore_bytes_per_sec" : "50mb",
        "compress" : true
    }
}
'

# 指定备份的索引逗号分隔，不传默认备份所有索引     "indices": "index1,index2"
# 全部时是会包括kibana的这些索引
curl -XPUT "http://localhost:9200/_snapshot/backup/snapshot_20201204?pretty&wait_for_completion=true" -H 'Content-Type: application/json' -d'
{
}
'
#查看备份状态
curl -XGET "http://localhost:9200/_snapshot/backup/snapshot_20201204?pretty"

#删除测试的快照和数据
curl -XDELETE "http://localhost:9200/_snapshot/backup/snapshot_2020120*?pretty"
rm -rf ../esdata/backup/*

## 对特定的索引进行备份
curl -XPUT http://localhost:9200/test/_doc/_bulk?pretty  -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
'
curl -XPUT http://localhost:9200/test2/_doc/_bulk?pretty -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
'
#批量索引的备份
curl -XPUT "http://localhost:9200/_snapshot/backup/snapshot_20201204?pretty&wait_for_completion=true" -H 'Content-Type: application/json' -d'
{
  "indices": "test*"
}
'

#增加部分内容后再次备份，可以验证是增量部分
#file:///hdd/test/built-docs-master/raw/en/elasticsearch/reference/master/snapshots-take-snapshot.html
#The snapshot process is incremental. In the process of making the snapshot, Elasticsearch analyses the list of the data stream and index files that are already stored in the repository and copies only files that were created or changed since the last snapshot. This process allows multiple snapshots to be preserved in the repository in a compact form.
curl -XPUT http://localhost:9200/test/_doc/_bulk?pretty  -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
'
curl -XPUT http://localhost:9200/test2/_doc/_bulk?pretty  -H 'Content-Type: application/json' -d'
{"index":{}}
{"message":"hello-01"}
{"index":{}}
{"message":"hello-02"}
{"index":{}}
{"message":"hello-03"}
'
curl -XPUT "http://localhost:9200/_snapshot/backup/snapshot_20201205?pretty&wait_for_completion=true" -H 'Content-Type: application/json' -d'
{
  "indices": "test*"
}
'

#看快照列表
curl -XGET "http://localhost:9200/_snapshot/backup/_all?pretty"